package elastic.onestep.index;

import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class EsBaiduQAIndexer extends EsIndexer {

    public EsBaiduQAIndexer(String indice, String type, String filepath) {
        super(indice, type, filepath);
    }

    @Override
    protected void map() throws IOException {
        PutMappingResponse pmr=null;
        try{
            XContentBuilder mapping =XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("qid").field("type","keyword").field("store",true).endObject()
                    .startObject("question").field("type","text").field("store",true).endObject()
                    .startObject("evidenceCount").field("type","keyword").field("store","true").endObject()
                    .endObject()
                    .endObject();
            System.out.println(mapping);
            pmr=client.admin().indices().preparePutMapping(indice).setType(type).setSource(mapping).get();
        }catch (IOException e){
            e.printStackTrace();
        }
        System.out.println(pmr.isAcknowledged());
    }

    @Override
    protected void processFile(File file, BulkProcessor bulkProcessor) {
        if (file.isFile()){
            //单个文件处理
            try {
                System.out.println("单个文件处理："+file.getCanonicalPath());
                BufferedReader reader=new BufferedReader(new FileReader(file));
                String json;
                while ((json=reader.readLine())!=null){
                    JSONObject jsonObject= JSONObject.parseObject(json);
                    bulkProcessor.add(upsert(jsonObject.getString("qid"),json));

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            for(File f:file.listFiles()){
                processFile(f,bulkProcessor);
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        EsBaiduQAIndexer esBaiduQAIndexer=new EsBaiduQAIndexer("qa3","baidu","/Users/unclewang/Idea_Projects/unclewang/src/main/resources/json/question.json");
        esBaiduQAIndexer.index();
    }
}
